package com.jihox.abookpro.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.os.Environment;
import android.util.Log;

import com.jihox.abookpro.R;
import com.jihox.abookpro.domain.ImageInfo;
import com.jihox.abookpro.domain.PagePicture;
import com.jihox.abookpro.domain.PictureHolder;

public class PictureUtil {

	public static boolean isSuitablePicture(int dpi,PagePicture pagePicture) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		
		ImageInfo imageInfo = pagePicture.getImage();
		BitmapFactory.decodeFile(imageInfo.getPath(), options);
		
		int imageMinHeight = (int) (imageInfo.getHeight()/25.4*dpi);
		int imageMinWidth = (int) (imageInfo.getWidth()/25.4*dpi);

		return imageMinHeight <= options.outHeight || imageMinWidth <= options.outWidth;
	}

	public static Bitmap readBitMap(Context context, int resId) {
		Bitmap bm =null;
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		try {
			// 获取资源图片
			InputStream is = context.getResources().openRawResource(resId);
			bm =  BitmapFactory.decodeStream(is, null, opt);
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bm;
	}

	public static Bitmap getBitmapFromAssetsFile(Context context ,String fileName)  
	{  
		Bitmap bitmap = null;  
		AssetManager am = context.getResources().getAssets();  
		try  
		{  
			InputStream is = am.open(fileName);  
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inPurgeable = true;
			options.inInputShareable = true;
			//options.inSampleSize = 2;
			bitmap = BitmapFactory.decodeStream(is, null, options);  
			is.close();  
		}  
		catch (IOException e)  
		{  
			if(bitmap==null){
				bitmap =( (BitmapDrawable)(context.getResources().getDrawable(R.drawable.pictures_no))).getBitmap();
			}
		}  
		return bitmap;  
	}  
	
	public static Bitmap getThumbFromAssetsFile(Context context ,String fileName,int width,int height)  
	{  
		Bitmap bitmap = null;  
		AssetManager am = context.getResources().getAssets();  
		try  
		{  
			InputStream is = am.open(fileName);  
	
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.outWidth =width;
			options.outHeight =height;
			options.inSampleSize=2;
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = false;
			bitmap = BitmapFactory.decodeStream(is, null, options);  
			
			is.close();  
		}  
		catch (IOException e)  
		{  
			if(bitmap==null){
				bitmap =( (BitmapDrawable)(context.getResources().getDrawable(R.drawable.pictures_no))).getBitmap();
			}
		}  
		return bitmap;  
	}  
	
	//从SD卡取素材图片
	public static Bitmap getThumbFromSDcard(Context context ,String path,int width,int height){  
	
		Bitmap bitmap = null;  
//		AssetManager am = context.getResources().getAssets();  
		try  
		{  
			File file = new File(Environment.getExternalStorageDirectory(), path);
			Log.d("路径", path + "");
			Log.d("file", file.getName() + "");
			InputStream ims = null;
			if (Environment.getExternalStorageState().equals(
	                Environment.MEDIA_MOUNTED)) {
				try {
					ims = new FileInputStream(file);
				} catch (Exception e) {
					e.printStackTrace();
				}
	         }
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.outWidth =width;
			options.outHeight =height;
			options.inSampleSize=2;
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = false;
			bitmap = BitmapFactory.decodeStream(ims, null, options);  
			if (ims!=null){
				ims.close(); 
			}
			
			//Log.d("bitmap", bitmap.getHeight() + "");
		}  
		catch (IOException e)  
		{  
			if(bitmap==null){
				bitmap =( (BitmapDrawable)(context.getResources().getDrawable(R.drawable.pictures_no))).getBitmap();
			}
		}  
		return bitmap;  
	}  
	
	public static Bitmap getThumbFromSDcard(Context context ,String path){  
		
		Bitmap bitmap = null;  
//		AssetManager am = context.getResources().getAssets();  
		try  
		{  
			File file = new File(Environment.getExternalStorageDirectory(), path);
			Log.d("路径", path + "");
			Log.d("file", file.getName() + "");
			InputStream ims = null;
			if (Environment.getExternalStorageState().equals(
	                Environment.MEDIA_MOUNTED)) {
				try {
					ims = new FileInputStream(file);
				} catch (Exception e) {
					e.printStackTrace();
				}
	         }
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = false;
			bitmap = BitmapFactory.decodeStream(ims, null, options);  
			if (ims!=null){
				ims.close(); 
			}
			
			//Log.d("bitmap", bitmap.getHeight() + "");
		}  
		catch (IOException e)  
		{  
			if(bitmap==null){
				bitmap =( (BitmapDrawable)(context.getResources().getDrawable(R.drawable.pictures_no))).getBitmap();
			}
		}  
		return bitmap;  
	}  
	
	//从SD卡取素材图片
	public static Bitmap decodeFileThumb(Context context ,String path){  
		Bitmap bitmap = null;  
		try  
		{  
			File file = new File(path);
			Log.d("路径", path + "");
			Log.d("file", file.getName() + "");
			InputStream ims = null;
			if (Environment.getExternalStorageState().equals(
	                Environment.MEDIA_MOUNTED)) {
				try {
					ims = new FileInputStream(file);
				} catch (Exception e) {
					e.printStackTrace();
				}
	         }
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inPreferredConfig = Bitmap.Config.RGB_565;
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(path, options);
			int largeSide = (options.outWidth>options.outHeight? options.outWidth:options.outHeight);
			options.inSampleSize = (int) (Math.rint(largeSide/1000));

			options.inSampleSize=2;
			options.inPurgeable = true;
			options.inInputShareable = true;
			options.inJustDecodeBounds = false;
			bitmap = BitmapFactory.decodeStream(ims, null, options);  
			ims.close(); 
			Log.d("bitmap", bitmap.getHeight() + "");
		}  
		catch (IOException e)  
		{  
			if(bitmap==null){
				bitmap =( (BitmapDrawable)(context.getResources().getDrawable(R.drawable.pictures_no))).getBitmap();
			}
		}  
		return bitmap;  
	}  
	
	
	public static Drawable getDrawableFromAssetsFile(Context context ,String fileName)  
	{  
		Drawable drawable = new BitmapDrawable(getBitmapFromAssetsFile(context, fileName));  
		return drawable;  

	}  

	public static Bitmap readBitMap(String fileName,BitmapFactory.Options options) {
		Bitmap bm =null;

		try {
			// 获取资源图片
			InputStream is = new FileInputStream(fileName);
			options.inPurgeable = true;
			options.inInputShareable = true;
			bm =  BitmapFactory.decodeStream(is, null, options);
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bm;
	}


	public static void cropAndCompressImage(String fileName,String outFilePath,PagePicture pagePicture,int dpi) {
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		ImageInfo imageInfo = pagePicture.getImage();
		PictureHolder holder = pagePicture.getHolder();
		
		//设置为true,表示解析Bitmap对象，该对象不占内存
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(fileName, options);
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		int pixel = (int) ((imageInfo.getHeight()/25.4*dpi)*(imageInfo.getWidth()/25.4*dpi));
		
		int w = options.outWidth; // 得到图片的宽，高
        int h = options.outHeight;
		
		int retX = (int) (imageInfo.getX()* w/imageInfo.getWidth());
        int retY = (int) (imageInfo.getY()*h/imageInfo.getHeight());
        int cropedHeight = (int) (holder.getHeight()*h/imageInfo.getHeight());
        int cropedWidth = (int) (holder.getWidth()*w/imageInfo.getWidth());
		
		options.inSampleSize = computeSampleSize(cropedWidth,cropedHeight, -1, pixel);
		//设置为false,解析Bitmap对象加入到内存中
		options.inJustDecodeBounds = false;
		options.inPurgeable = true;
		options.inInputShareable = true;
		int degree = PictureUtil.readPictureDegree(fileName);
		Bitmap bitmap = null;
		if (degree != 0) {// 旋转照片角度
			bitmap =  PictureUtil.rotateBitmap(BitmapFactory.decodeFile(fileName, options), degree);
		}
		else{
			bitmap = BitmapFactory.decodeFile(fileName, options);
		}
		
		w = bitmap.getWidth(); // 得到图片的宽，高
        h = bitmap.getHeight();
		
		retX = (int) (imageInfo.getX()* w/imageInfo.getWidth());
        retY = (int) (imageInfo.getY()*h/imageInfo.getHeight());
        cropedHeight = (int) (holder.getHeight()*h/imageInfo.getHeight());
        cropedWidth = (int) (holder.getWidth()*w/imageInfo.getWidth());

        Bitmap newBitmap = Bitmap.createBitmap(bitmap,Math.abs(retX), Math.abs(retY), (int)cropedWidth, (int)cropedHeight, null, false);

        // save file
		File myCaptureFile = new File(outFilePath);
		FileOutputStream out;
		try {
			out = new FileOutputStream(myCaptureFile);
			
			if (newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)) {
 				out.flush();
 				out.close();
 			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (!bitmap.isRecycled()){
			bitmap.recycle();
			bitmap =null;
		}
		if (!newBitmap.isRecycled()) {
			newBitmap.recycle();
			newBitmap = null;
		}
    }
	
//	/*
//	 * 压缩图片，处理某些手机拍照角度旋转的问题
//	 */
//	public static void compressImage(String filePath, String outFilePath,
//			int reqSize) throws IOException {
//
//		try {
//
//			BitmapFactory.Options options = new BitmapFactory.Options();
//			options.inJustDecodeBounds = true;
//			BitmapFactory.decodeFile(filePath, options);
//			options.inSampleSize = computeSampleSize(options, -1, reqSize
//					* reqSize);
//			options.inJustDecodeBounds = false;
//			options.inPurgeable = true;
//			options.inInputShareable = true;
//			Bitmap resizedBitmap = BitmapFactory.decodeFile(filePath, options);
//
//			int degree = readPictureDegree(filePath);
//			if (degree != 0) {// 旋转照片角度
//				resizedBitmap = rotateBitmap(resizedBitmap, degree);
//			}
//
//			// save file
//			File myCaptureFile = new File(outFilePath);
//			FileOutputStream out = new FileOutputStream(myCaptureFile);
//			if (resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out)) {
//				out.flush();
//				out.close();
//			}
//
//			if (!resizedBitmap.isRecycled()) {
//				resizedBitmap.recycle();
//			}
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//			throw e;
//		} catch (IOException ex) {
//			ex.printStackTrace();
//			throw ex;
//		}
//	}

	public static int computeSampleSize(int width,int height,
			int minSideLength, int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(width,height, minSideLength,
				maxNumOfPixels);

		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	private static int computeInitialSampleSize(int width,int height,
			int minSideLength, int maxNumOfPixels) {

		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(width * height / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(width / minSideLength), Math.floor(height / minSideLength));

		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	public static Bitmap rotateBitmap(Bitmap bitmap, int degress) {
		if (bitmap != null) {
			Matrix m = new Matrix();
			m.postRotate(degress);
			bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
					bitmap.getHeight(), m, true);
			return bitmap;
		}
		return bitmap;
	}
}
